package com.ctshk.rpc.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.appUser.TransactionIntegralStatus;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.user.dto.TransactionIntegralLogDTO;
import com.ctshk.rpc.user.entity.TransactionIntegralLog;
import com.ctshk.rpc.user.mapper.TransactionIntegralLogMapper;
import com.ctshk.rpc.user.req.TransactionIntegralLogReq;
import com.ctshk.rpc.user.service.ITransactionIntegralLogService;
import org.apache.dubbo.config.annotation.DubboService;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author 李新科
 * @date 2021/6/29 17:16
 */
@DubboService(validation = "true")
public class TransactionIntegralLogServiceImpl extends ServiceImpl<TransactionIntegralLogMapper, TransactionIntegralLog> implements ITransactionIntegralLogService {

    @Override
    public Long save(@Valid TransactionIntegralLogReq req) {
        TransactionIntegralLog entity = EntityUtil.copy(req, TransactionIntegralLog.class);
        LocalDateTime now = LocalDateTime.now();
        long id = SnowflakeIdWorker.nextId();
        entity.setId(id);
        entity.setStatus(TransactionIntegralStatus.NEW.getCode());
        entity.setIsDeleted(IsDeletedCode.NO.getCode());
        entity.setGmtCreate(now);
        entity.setGmtModified(now);
        baseMapper.insert(entity);
        return id;
    }

    @Override
    public void update(TransactionIntegralLogReq req) {
        TransactionIntegralLog entity = EntityUtil.copy(req, TransactionIntegralLog.class);
        LocalDateTime now = LocalDateTime.now();
        entity.setCtsTxnCardNum(req.getCtsTXNCardNum());
        entity.setCtsPointSubType(req.getCtsPointSubType());
        entity.setCtsPointSubTypeCode(req.getCtsPointSubTypeCode());
        entity.setCtsTransactionChannelSn(req.getCtsTransactionChannelSN());
        entity.setGmtModified(now);
        baseMapper.updateById(entity);
    }

    @Override
    public List<TransactionIntegralLogDTO> selectListByOrderId(Long orderId) {
        return EntityUtil.copyList(baseMapper.selectList(Wrappers.<TransactionIntegralLog>lambdaQuery()
                .eq(TransactionIntegralLog::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(TransactionIntegralLog::getOrderId, orderId)),TransactionIntegralLogDTO.class);
    }

    @Override
    public boolean exists(Long orderId, String transactionType) {
        Integer count = baseMapper.selectCount(Wrappers.<TransactionIntegralLog>lambdaQuery()
                .eq(TransactionIntegralLog::getOrderId, orderId)
                .eq(TransactionIntegralLog::getTransactionType, transactionType)
        );
        return count > 0?true:false;
    }
}
